package com.rop.znyx.activity.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rop.znyx.activity.mapper.ActivityInfoMapper;
import com.rop.znyx.activity.mapper.ActivityRuleMapper;
import com.rop.znyx.activity.mapper.ActivitySkuMapper;
import com.rop.znyx.activity.mapper.CouponInfoMapper;
import com.rop.znyx.activity.service.ActivityInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.activity.service.CouponInfoService;
import com.rop.znyx.common.result.Result;
import com.rop.znyx.enums.ActivityType;
import com.rop.znyx.model.activity.CouponInfo;
import com.rop.znyx.product.ProductFeignClient;
import com.rop.znyx.model.activity.ActivityInfo;
import com.rop.znyx.model.activity.ActivityRule;
import com.rop.znyx.model.activity.ActivitySku;
import com.rop.znyx.model.product.SkuInfo;
import com.rop.znyx.vo.activity.ActivityRuleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author rop
 * @since 2023-07-09
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements ActivityInfoService {

    private final ActivityRuleMapper activityRuleMapper;

    private final ActivitySkuMapper activitySkuMapper;

    private final ProductFeignClient productFeignClient;

    private final ActivityInfoMapper activityInfoMapper;

    private final CouponInfoService couponInfoService;

    /**
     * 获取营销活动分页列表
     */
    @Override
    public IPage<ActivityInfo> selectPage(Page<ActivityInfo> pageParam) {
        QueryWrapper<ActivityInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        IPage<ActivityInfo> activityInfoPage = baseMapper.selectPage(pageParam, queryWrapper);

        activityInfoPage.getRecords().forEach(a -> a.setActivityTypeString(a.getActivityType().getComment()));

        return activityInfoPage;
    }

    /**
     * 营销活动规则相关接口
     *
     * @param id 营销活动id
     */
    @Override
    public Map<String, Object> findActivityRuleList(Long id) {
        Map<String, Object> result = new HashMap<>();

        // 营销活动规则
        QueryWrapper<ActivityRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", id);
        List<ActivityRule> activityRuleList = activityRuleMapper.selectList(queryWrapper);
        result.put("activityRuleList", activityRuleList);

        // sku
        QueryWrapper<ActivitySku> activitySkuQueryWrapper = new QueryWrapper<>();
        activitySkuQueryWrapper.eq("activity_id", id);
        List<ActivitySku> activitySkuList = activitySkuMapper.selectList(activitySkuQueryWrapper);
        List<Long> skuIdList = activitySkuList.stream().map(ActivitySku::getSkuId).collect(toList());
        List<SkuInfo> skuInfoList = productFeignClient.findSkuInfoList(skuIdList).getData();
        result.put("skuInfoList", skuInfoList);
        return result;
    }

    /**
     * 新增活动规则
     *
     * @param activityRuleVo 活动规则实体
     */
    @Override
    @Transactional
    public void saveActivityRule(ActivityRuleVo activityRuleVo) {
        // 先删除
        Long activityId = activityRuleVo.getActivityId();
        activityRuleMapper.delete(new QueryWrapper<ActivityRule>().eq("activity_id", activityId));
        activitySkuMapper.delete(new QueryWrapper<ActivitySku>().eq("activity_id", activityId));

        // 再新增
        List<ActivityRule> activityRuleList = activityRuleVo.getActivityRuleList();
        List<ActivitySku> activitySkuList = activityRuleVo.getActivitySkuList();

        ActivityInfo activityInfo = activityInfoMapper.selectById(activityRuleVo.getActivityId());
        activityRuleList.forEach(ar -> {
            ar.setActivityId(activityId);
            ar.setActivityType(activityInfo.getActivityType());
        });
        activityRuleMapper.batchInsert(activityRuleList);

        activitySkuList.forEach(as -> as.setActivityId(activityId));
        activitySkuMapper.batchInsert(activitySkuList);
    }

    /**
     * 根据关键字获取sku信息
     */
    @Override
    public List<SkuInfo> findSkuInfoByKeyword(String keyword) {
        return productFeignClient.findSkuInfoByKeyword(keyword).getData();
    }

    /**
     * 根据skuId列表获取促销信息
     */
    @Override
    public Result<Map<Long, List<String>>> findActivity(List<Long> skuIdList) {
        Map<Long, List<String>> map = new HashMap<>();
        //skuIdList遍历，得到每个skuId
        skuIdList.forEach(skuId -> {
            //根据skuId进行查询，查询sku对应活动里面规则列表
            List<ActivityRule> activityRuleList = baseMapper.findActivityRule(skuId);
            //数据封装，规则名称
            if (CollUtil.isNotEmpty(activityRuleList)) {
                List<String> ruleList = new ArrayList<>();
                //把规则名称处理
                for (ActivityRule activityRule : activityRuleList) {
                    ruleList.add(this.getRuleDesc(activityRule));
                }
                map.put(skuId, ruleList);
            }
        });
        return Result.ok(map);
    }

    private String getRuleDesc(ActivityRule activityRule) {
        ActivityType activityType = activityRule.getActivityType();
        StringBuilder ruleDesc = new StringBuilder();
        if (activityType == ActivityType.FULL_REDUCTION) {
            ruleDesc
                    .append("满")
                    .append(activityRule.getConditionAmount())
                    .append("元减")
                    .append(activityRule.getBenefitAmount())
                    .append("元");
        } else {
            ruleDesc
                    .append("满")
                    .append(activityRule.getConditionNum())
                    .append("元打")
                    .append(activityRule.getBenefitDiscount())
                    .append("折");
        }
        return ruleDesc.toString();
    }

    @Override
    public Map<String, Object> findActivityAndCoupon(Long skuId, Long userId) {
        //一个sku只能有一个促销活动，一个活动有多个活动规则（如满赠，满100送10，满500送50）
        List<ActivityRule> activityRuleList = this.findActivityRuleBySkuId(skuId);

        //获取优惠券信息
        List<CouponInfo> couponInfoList = couponInfoService.findCouponInfo(skuId, userId);

        Map<String, Object> map = new HashMap<>();
        map.put("activityRuleList", activityRuleList);
        map.put("couponInfoList", couponInfoList);
        return map;
    }

    //根据skuId获取活动规则数据
    public List<ActivityRule> findActivityRuleBySkuId(Long skuId) {
        List<ActivityRule> activityRuleList = baseMapper.findActivityRule(skuId);
        for (ActivityRule activityRule : activityRuleList) {
            String ruleDesc = this.getRuleDesc(activityRule);
            activityRule.setRuleDesc(ruleDesc);
        }
        return activityRuleList;
    }
}
